package cn.edu.pku.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by ming.qin on 2017/5/9.
 */
@Configuration
@Component
@Slf4j
public class CorsConfig implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        log.info(request.getRequestURI());
//        if (!StringUtils.endsWithIgnoreCase("/login", request.getRequestURI())
//                && !StringUtils.endsWithIgnoreCase("/logout", request.getRequestURI())) {
//            HttpSession session = request.getSession();
//            String token = getToken(request);
//            if (StringUtils.isEmpty(token) || session.getAttribute(token) == null) {
//                PrintWriter writer = response.getWriter();
//                String json = "{\"status\":-1,\"message\":\"need login\"}";
//                writer.write(json);
//                writer.flush();
//                return;
//            }
//        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    private String getToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            token = request.getParameter("token");
            if (StringUtils.isEmpty(token)) {
                Cookie[] cookies = request.getCookies();
                for (int i = 0; i < cookies.length; i++) {
                    Cookie c = cookies[i];
                    if (StringUtils.endsWithIgnoreCase(c.getName(), "token")) {
                        token = c.getValue();
                        break;
                    }
                }
            }
        }
        return token;
    }

    @Override
    public void destroy() {

    }
}
